package com.hpin.fansea.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.fansea.R;
import com.hpin.fansea.adapter.BannerAdapter;
import com.hpin.fansea.adapter.ServiceModuleAdapter;
import com.hpin.fansea.base.BaseFragment;
import com.hpin.fansea.bean.BannerResult;
import com.hpin.fansea.service.ExpressActivity;
import com.hpin.fansea.service.GetWaterActivity;
import com.hpin.fansea.service.HouseKeepingActivity;
import com.hpin.fansea.service.HouseRentActivity;
import com.hpin.fansea.service.WashCarActivity;
import com.hpin.fansea.service.WashClothesActivity;
import com.hpin.fansea.utils.Constant;
import com.hpin.fansea.utils.HttpUtil;
import com.hpin.fansea.utils.LogUtil;
import com.hpin.fansea.widget.GridViewForScrollView;
import com.lidroid.xutils.http.RequestParams;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

/**
 *特约服务fragment
 * Created by Administrator on 2015/7/15.
 */
public class ServiceFragment extends BaseFragment implements View.OnClickListener {

    private Intent mIntent;
    private List<BannerResult.BannerDetail> bannerLists=new ArrayList<BannerResult.BannerDetail>();
    private BannerAdapter mAdapter;
    private ViewPager vp_servicepage;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = View.inflate(getActivity(), R.layout.fragment_engaged_service, null);

        initWidget(view);

        // 加载轮播图
        getBunnerFromNet();

        return view;

    }

    private void initWidget(View view) {

        GridViewForScrollView gv_module = (GridViewForScrollView) view.findViewById(R.id.gv_module);

        vp_servicepage = (ViewPager) view.findViewById(R.id.vp_servicepage);

        ServiceModuleAdapter serviceModuleAdapter = new ServiceModuleAdapter(getActivity());
        gv_module.setAdapter(serviceModuleAdapter);

        gv_module.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {

                    case 0:         //家政

                        mIntent = new Intent(getActivity(), HouseKeepingActivity.class);
                        startActivity(mIntent);

                        break;
                    case 1:         //洗车

                        mIntent = new Intent(getActivity(), WashCarActivity.class);
                        startActivity(mIntent);

                        break;
                    case 2:         //洗衣

                        mIntent = new Intent(getActivity(), WashClothesActivity.class);
                        startActivity(mIntent);

                        break;
                    case 3:         //快递服务

                        mIntent = new Intent(getActivity(), ExpressActivity.class);
                        startActivity(mIntent);

                        break;
                    case 4:         //房屋租售

                        mIntent = new Intent(getActivity(), HouseRentActivity.class);
                        startActivity(mIntent);

                        break;
                    case 5:         //送水

                        mIntent = new Intent(getActivity(), GetWaterActivity.class);
                        startActivity(mIntent);

                        break;

                }

            }
        });
    }

    /**
     * 获取轮播图
     */
    private void getBunnerFromNet() {

        RequestParams params = new RequestParams();

        params.addQueryStringParameter("systemType", Constant.SYSTEM_TYPE);
        params.addQueryStringParameter("location", Constant.SERVERPAGER);
        params.addQueryStringParameter("projectId", sp.getString(Constant.communityId, ""));

        HttpUtil.getInstance().setGetRequest("加载中...", getActivity(), Constant.WEB_ROOT + Constant.GETBUNNER, params, new HttpUtil.SuccessListener() {
            @Override
            public void setOnSuccessListener(String str) {

                try {

                    BannerResult bannerResult = JSONObject.parseObject(str, BannerResult.class);

                    if (Constant.STATUS_SUCESS.equals(bannerResult.status)) {

                        bannerLists = bannerResult.result;

                        mAdapter = new BannerAdapter(bannerLists, getActivity());
                        vp_servicepage.setAdapter(mAdapter);

                        //开始轮播
                        startPlay();

                    }else {
                        showToast(bannerResult.message);
                    }

                }catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, null);

    }

    private boolean actionNotDown = true;
    private static final int CHANGEPIC = 005;

    /**
     * 开始轮播
     */
    private void startPlay() {

        //设置无限轮播的起点
        if (bannerLists==null || bannerLists.size()==0 )
            return;

        int middle =  Constant.MAX_SIZE / 2 ;

        int firstItem = (middle / bannerLists.size()) * bannerLists.size();

        LogUtil.e("tag", "firstItem===" + firstItem);

        vp_servicepage.setCurrentItem((middle / bannerLists.size()) * bannerLists.size());

        vp_servicepage.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            /**
             * 当页面选择发生改变的时候，
             * position 新页面的下标
             */
            public void onPageSelected(int position) {

            }

            @Override
            /**
             * 当页面滑动时的回调监听
             */
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

//                 LogUtil.e("tag", "onPageScrolled===" + position);

                currentPosition = position;
            }

            @Override
            /**
             * 当页面的滑动状态发生改变的时候，
             * 如：手指按下状诚，滑动状态，抬起状态
             */
            public void onPageScrollStateChanged(int state) {
            }
        });

        vp_servicepage.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                actionNotDown = false;
                return false;
            }
        });

        // 让轮播图滚动
        if (isStop) {
            startRoll();
            isStop = false;
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

//        LogUtil.e("TAG", "homepagefragment=====onDestroyView");

        isStop = false;
    }
    /**
     * 让轮播图滚动
     */
    public void startRoll() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                SystemClock.sleep(Constant.MSG_DELAY);
                handler.sendEmptyMessage(CHANGEPIC);
            }
        }).start();

    }

    private int currentPosition;
    private int item;
    private boolean isStop = true;

    private Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case CHANGEPIC:

                    if (actionNotDown) {

                        //做判断 以防万一
                        if (bannerLists==null || bannerLists.size()==0 || bannerLists.size() == 1)
                            return;

                        item = (currentPosition++) % (bannerLists.size());
                        vp_servicepage.setCurrentItem(item, false);
                    }else {
                        actionNotDown = true;
                    }
                    startRoll();
                    break;
                default:
                    break;
            }

        }
    };

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getName());
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.tv_left:
//                //工作
//
//                Intent intent = new Intent(getActivity(), WorkActivity.class);
//                getActivity().startActivity(intent);
//
//                break;
//            case R.id.tv_right:
//                //列表
//                Intent mIntent = new Intent(getActivity(), ChildListActivity.class);
//                mIntent.putExtra("tempList", (Serializable) tempList);
//                startActivity(mIntent);
//                break;
        }
    }


}
